<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="账户Id">
                <a-input
                  :style="{width: '100%'}"
                  v-model="queryParam.accountId"
                  placeholder="请输入账户Id" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="微信群">
                <a-input
                  :style="{width: '100%'}"
                  v-model="queryParam.wechatName"
                  placeholder="请输入微信群" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="代理商名称">
                <a-input
                  :style="{width: '100%'}"
                  v-model="queryParam.supplierName"
                  placeholder="请输入代理商名称" />
              </a-form-item>
            </a-col>
            <a-col
              :md="3"
              :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button
                  type="primary"
                  v-if="list"
                  @click="searchSupplier">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  v-if="list"
                  @click="() => {this.queryParam = {};this.$refs.table.refresh() }">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button
          type="primary"
          icon="plus"
          v-if="save"
          @click="addBaseData">新建</a-button>
      </div>
      <div>
        <s-table
          ref="table"
          size="default"
          rowKey="baseDataId"
          :columns="columns"
          :data="loadData"
          showPagination="auto"
          :scroll="{ x: 1900 }">
          <span
            slot="serial"
            slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span
            slot="status"
            slot-scope="text">
            <a-badge
              :status="text | statusTypeFilter"
              :text="text | statusFilter" />
          </span>
          <span
            slot="description"
            slot-scope="text">
            <ellipsis
              :length="4"
              tooltip>{{ text }}</ellipsis>
          </span>

          <span
            slot="action"
            slot-scope="text, record">
            <template>
              <a v-if="update" @click="handleEditBaseData(record)">配置</a>
              <a-divider type="vertical" />
              <a v-if="update" @click="handleUpdateBaseData(record)">更新返点</a>
              <a-divider type="vertical" />
              <a v-if="deleteBtn" @click="handleDeleteBaseData(record)">删除</a>
            </template>
          </span>
        </s-table>
      </div>

      <base-data-create-form
        ref="baseDataCreatForm"
        :visible="baseDataCreateVisible"
        :loading="baseDataLoading"
        :customers="customers"
        :suppliers="suppliers"
        :users="users"
        :supplierTypes="supplierTypes"
        @cancel="handleCancel"
        @ok="baseDataCreateOK" />
      <base-data-edit-form
        ref="baseDataEditForm"
        :visible="baseDataEditVisible"
        :loading="baseDataLoading"
        :customers="customers"
        :suppliers="suppliers"
        :users="users"
        :supplierTypes="supplierTypes"
        @cancel="handleCancel"
        @ok="baseDataEditOK" />
      <base-data-update-form
        ref="baseDataUpdateForm"
        :visible="baseDataUpdateVisible"
        :loading="baseDataLoading"
        :customers="customers"
        :suppliers="suppliers"
        :users="users"
        :supplierTypes="supplierTypes"
        @cancel="handleCancel"
        @ok="baseDataUpdateOK" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
// import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import {
  baseDataUpdate,
  baseDataDelete,
  baseDataUpdateDiscount,
  baseDataInfo,
  getAllCustom,
  supplierSelectLast,
  allStaff,
  baseDataSave,
  supplierTypes
} from '@/api/manage'

import BaseDataCreateForm from './modules/DemandCreateForm'
import BaseDataEditForm from './modules/DemandEditForm'
import baseDataUpdateForm from './modules/DemandUpdateForm'
import { columns } from './config'
import { message, Modal } from 'ant-design-vue'
import { isInMenu } from '../config.js'
import { mapGetters } from 'vuex'

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    BaseDataCreateForm,
    BaseDataEditForm,
    baseDataUpdateForm
  },
  data () {
    this.columns = columns
    return {
      // 权限参数
      list: false, // 查
      save: false, // 加
      deleteBtn: false, // 删
      update: false, // 改

      baseDataCreateVisible: false,
      baseDataEditVisible: false,
      baseDataUpdateVisible: false,

      baseDataLoading: false,

      baseData: undefined,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      prodlist: [],
      contacts: [],
      supplier: undefined,

      // 客户
      customers: [],
      // 代理商
      suppliers: [],
      // 员工
      users: [],
      // 代理商类型
      supplierTypes: [],

      contactTabLoading: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = { page: parameter.pageNo, limit: parameter.pageSize }
        const param = Object.assign({}, this.queryParam)
        return (
          this.list &&
          baseDataInfo(
            Object.assign({}, param, requestParameters)
          ).then(res => {
            return Object.assign({}, res, {
              totalCount: res.total,
              pageNo: parameter.pageNo,
              pageSize: parameter.pageSize
            })
          })
        )
      },
      // staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      physicalSurveyCurrRowId: null
    }
  },
  created () {
    // 点击查看
    this.list =
      isInMenu(this.menu, 'ROLE_but:supplier:list') &&
      isInMenu(this.menu, 'ROLE_but:supplier:info') &&
      isInMenu(this.menu, 'ROLE_but:contact:info') &&
      isInMenu(this.menu, 'ROLE_but:contact:list')
    // 增加
    this.save =
      isInMenu(this.menu, 'ROLE_but:supplier:save') &&
      isInMenu(this.menu, 'ROLE_but:contact:save') &&
      isInMenu(this.menu, 'ROLE_but:product:select')
    // 改
    this.update =
      isInMenu(this.menu, 'ROLE_but:supplier:update') &&
      isInMenu(this.menu, 'ROLE_but:contact:update') &&
      isInMenu(this.menu, 'ROLE_but:product:select')
    // 删除
    this.deleteBtn = isInMenu(this.menu, 'ROLE_but:supplier:delete') && isInMenu(this.menu, 'ROLE_but:contact:delete')
  },
  computed: {
    ...mapGetters(['menu']),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows,
        onChange: this.onSelectChange
      }
    }
  },
  mounted () {
    getAllCustom({}).then(res => {
      if (res.code === 0) {
        this.customers = res.data
      }
    })

    supplierSelectLast({}).then(res => {
      if (res.code === 0) {
        this.suppliers = res.data
      }
    })

    allStaff({}).then(res => {
      if (res.code === 0) {
        this.users = res.data
      }
    })

    supplierTypes({}).then(res => {
      if (res.code === 0) {
        this.supplierTypes = res.data
      }
    })
  },
  methods: {
    handleDeleteBaseData (record) {
      Modal.confirm({
        title: '删除基础数据',
        content: '删除后数据不再展示，需要查看请联系开发',
        onOk: () => {
          this.loading = true
          baseDataDelete({ baseDataId: record.baseDataId }).then(() => {
            message.success('删除成功')
            this.$refs.table.refresh()
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    // add 创新新的表格
    searchSupplier () {
      // const param = Object.assign({}, this.queryParam)
      this.$refs.table.refresh()
    },
    addBaseData () {
      this.baseData = null
      this.baseDataCreateVisible = true
    },
    // edit 展示表格 nextTick 并赋值
    handleEditBaseData (record) {
      this.baseData = { ...record }
      this.baseDataEditVisible = true
      const form = this.$refs.baseDataEditForm.form
      this.$nextTick(() => {
        const _custom = Object.assign({}, this.baseData)
        form.setFieldsValue(_custom)
      })
    },
    // update 展示表格 nextTick 并赋值
    handleUpdateBaseData (record) {
      this.baseData = { ...record }
      this.baseDataUpdateVisible = true
      const form = this.$refs.baseDataUpdateForm.form
      this.$nextTick(() => {
        const _custom = Object.assign({}, this.baseData)
        form.setFieldsValue(_custom)
      })
    },
    // 通过 ref 获取表格实例
    baseDataCreateOK () {
      const form = this.$refs.baseDataCreatForm.form
      this.baseDataLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          const param = Object.assign({}, values)
          baseDataSave(param).then(res => {
            if (res.code === 0) {
              this.baseDataCreateVisible = false
              this.$refs.table.refresh()
              this.baseDataLoading = false
              this.$message.info('新增成功')
              form.resetFields()
            }
          }).finally(() => { this.baseDataLoading = false })
        }
        this.baseDataLoading = false
      })
    },
    baseDataEditOK () {
      const form = this.$refs.baseDataEditForm.form
      form.validateFields((errors, values) => {
        if (!errors) {
          const param = Object.assign({}, values, { baseDataId: this.baseData.baseDataId })
          baseDataUpdate(param).then(() => {
            this.baseDataLoading = false
            this.baseDataEditVisible = false
            this.$message.info('配置修改成功')
            form.resetFields()
            this.$refs.table.refresh()
          }).finally(() => { this.baseDataLoading = false })
        }
      })
    },
    baseDataUpdateOK () {
      const form = this.$refs.baseDataUpdateForm.form
      const baseData = this.baseData
      form.validateFields((errors, values) => {
        if (!errors) {
          const param = Object.assign({ baseDataId: baseData.baseDataId }, values)
          baseDataUpdateDiscount(param).then(res => {
            if (res.code === 0) {
              this.baseDataUpdateVisible = false
              this.$refs.table.refresh()
              this.baseDataLoading = false
              this.$message.info('更新成功')
              form.resetFields()
            }
          }).finally(() => { this.baseDataLoading = false })
        }
      })
    },
    handleCancel () {
      this.baseDataCreateVisible = false
      this.baseDataEditVisible = false
      this.baseDataUpdateVisible = false
      this.$refs.baseDataCreatForm.form.resetFields()
      this.$refs.baseDataEditForm.form.resetFields()
      this.$refs.baseDataUpdateForm.form.resetFields()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      // todo supplierId selectedRows array[supplierId]
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    }
  }
}
</script>
